package com.study.easyexcel.api.converter;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.converters.ReadConverterContext;
import com.alibaba.excel.converters.WriteConverterContext;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.study.easyexcel.common.enums.SexEnum;

/**
 * 性别转换器，将性别在中文和数字间自动映射{@link SexEnum}
 *
 * @author yuhuan
 * @date 2023/5/9
 */
public class SexConverter implements Converter<Integer> {

    private final static String MEN_STR = SexEnum.MEN.getValue();
    private final static int MEN_NUM = SexEnum.MEN.getSequence();
    private final static String WOMEN_STR = SexEnum.WOMEN.getValue();
    private final static int WOMEN_NUM = SexEnum.WOMEN.getSequence();

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }

    /**
     * 读的时候会调用
     */
    @Override
    public Integer convertToJavaData(ReadConverterContext<?> context) throws Exception {
        if (MEN_STR.equals(context.getReadCellData().getStringValue())) {
            return MEN_NUM;
        }
        if (WOMEN_STR.equals(context.getReadCellData().getStringValue())) {
            return WOMEN_NUM;
        }
        return SexEnum.UNKNOWN.getSequence();
    }

    /**
     * 写的时候会调用
     */
    @Override
    public WriteCellData<?> convertToExcelData(WriteConverterContext<Integer> context) throws Exception {
        if (MEN_NUM == context.getValue()) {
            return new WriteCellData<>(MEN_STR);
        }
        if (WOMEN_NUM == context.getValue()) {
            return new WriteCellData<>(WOMEN_STR);
        }
        return new WriteCellData<>(SexEnum.UNKNOWN.getValue());
    }
}
